package xdu.lz.netty.g_handler.tcp_粘包;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author Badribbit
 * @create 2019/4/14 21:46
 */

/**
 * nett即可以做客户端也可以做服务端
 * 一对一交互
 */
public class MyServer {
    public static void main(String[] args) throws  Exception{
        //事件循环组
        //只是完成了一些参数的赋值，并没有开启什么东西。 参数是开启线程的个数，不传则是CPU核数*2

        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).  //初始化时候会被 加入到 ServerBootstrapAcceptor   Reactor中的Acceptor
                    childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();

                    pipeline.addLast(new MyServerHandler());//入栈处理器
                }
            });

            //sync表示 bind完成后再返回ChannelFuture，不加的话执行会往下执行code。可能会出问题
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();

            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
